<template>
  <div class="seardh-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync = "error"
      error-text = "加载失败，请点击重试"
      @load="onLoad">
      <van-cell 
        v-for="(rusult,index) in list" :key="index" 
        :title="rusult.title" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResults } from "@/api/search";
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      perPage: 20,
      error: false
    }
  },
  methods: {
    async onLoad() {
      try {
        // 1.请求获取数据
        const { data } = await getSearchResults({
          page: this.page, //页码
          per_page: this.perPage, //每页大小
          q: this.searchText //查询关键词
        })
        // console.log(data)
        // if (Math.random() > 0.5) {
        //   JSON.parse('dasdhks')
        // }
        // 2.将数据添加到数组中
        const { results } = data.data
        this.list.push(...results)
        // 3.将本次加载中的 loading 关闭
        this.loading = false
        // 4.判断是否还有数据
        if (results.length) {
          // 如果有则更新获取下一个数据的页码
          this.page++
        } else {
          // 如果没有，则将加载状态 finished 设置为结束
          this.finished = true
        } 
      } catch (err) {
        this.error = true
        this.loading = false
        this.$toast('搜索结果数据获取失败')
      }
    },
  },
};
</script>

<style>

</style>